<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>网络聊天室</title>
</head>
<style>
	#contains {
		background-color: pink;
		width: 1000px;
		height: 700px;
		margin: auto;
	}

	#username {
		background-color: powderblue;
		width: 1000px;
		height: 30px;
	}

	#Inchat {
		background-color: rgb(5, 130, 146);
		width: 1000px;
		height: 30px;
	}

	#left {
		background-color: salmon;
		width: 700px;
		height: 640px;
		float: left;
		position: relative;
	}

	#content {
		background-color: silver;
		width: 700px;
		height: 400px;
		/*display: none;*/
		visibility: hidden;
	}

	#right {
		background-color: rgb(107, 3, 3);
		width: 300px;
		height: 640px;
		float: right;
	}

	#hyList {
		height: 270px;
		overflow-y: scroll;
		background: antiquewhite;
	}

	#xtList {
		height: 270px;
		overflow-y: scroll;
		background: antiquewhite;
	}

	#input {
		margin-bottom: 0px;
		position: absolute;
		bottom: 0px;
	}

	#mes_left {
		float: left;
		border: 2px aqua;
		max-width: 490px;
	}

	#mes_right {
		float: right;
		border: 2px aqua;
		max-width: 490px;
	}

	#hy {
		display: block;
		width: 300px;
	}

	textarea {
		resize: none;
		border: none;
		outline: none
	}
</style>
<body>
	<div id="contains">
		<div id="username"></div>
		<div id="Inchat"></div>
		<div id="left">
			<div id="content">

			</div>
			<div id="input">
				<textarea type="text" id="input_text" style="width: 695px;height: 200px;"></textarea>
				<button id="submit" style="float: right;">发送</button>
			</div>
		</div>
		<div id="right">
			<p id="hy" style="text-align: center;">好友列表</p>
			<div id="hyList">

			</div>
			<p id="xt" style="text-align: center">系统消息</p>
			<div id="xtList">

			</div>
		</div>
	</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
	let toName;
	let username;
	let websocket;

	function offline() {
		$.ajax({
			url: "offline",
			success: function (res) {

			},
		});
	}

	$(function () {
		$.ajax({
			url: "getUsername",
			success: function (res) {
				username = res.data;
			},
			async: false //同步请求，只有上面好了才会接着下面
		});
		let host = window.location.host;
		let ws = new WebSocket("ws://" + host + "/chat");
		getUsers();
		websocket = ws;
		//建立websocket连接
		//获取host解决后端获取httpsession的空指针异常
		ws.onopen = function (evt) {
			console.log(evt.data)
			$("#username").html("<h3 style=\"text-align: center;\">用户：" + username + "<span >-在线</span><span onclick=\"offline()\">-下线</span><span onclick=\"logout()\">-退出</span></h3>");
		}
		let broadcastListStr = "";
		//接受消息
		ws.onmessage = function (evt) {
			//获取服务端推送的消息
			let dataStr = evt.data;
			//将dataStr转换为json对象
			let res = JSON.parse(dataStr);
			console.log(res);
			//判断是否是系统消息
			if (res.system) {
				getUsers();
				//系统消息
				broadcastListStr += "<p style='text-align: center'>" + res.fromName + "---" + res.message + "</p>";
				$("#xtList").html(broadcastListStr);
			} else {
				//不是系统消息
				console.log(res);
				let str = "<span id='mes_left'>" + res.message + "</span></br>";
				$("#content").append(str);
				let chatData = sessionStorage.getItem(res.fromName);
				if (chatData != null) {
					str = chatData + str;
				}
				//保存聊天消息
				sessionStorage.setItem(res.fromName, str);
			}
		}
		ws.onclose = function () {
			$("#username").html("<h3 style=\"text-align: center;\">用户：" + username + "<span>-离线</span><span onclick='online()'>-上线</span><span onclick=\"logout()\">-退出</span></h3>");
		}
	})

	function online() {
		location.reload();
	}

	function logout() {
		$.ajax({
			url: "logout",
			success: function (res) {
				if (res.success) {
					location.href = "login.html";
				}
			},
		});
	}

	//点击好友名称展示相关消息
	function showChat(name) {
		console.log(name)
		toName = name;
		//现在聊天框
		$("#content").html("");
		$("#content").css("visibility", "visible");
		$("#Inchat").html("当前正与-" + toName + "-聊天");
		//从sessionStorage中获取历史信息
		let chatData = sessionStorage.getItem(toName);
		if (chatData != null) {
			$("#content").html(chatData);
		}
	}

	function getUsers() {
		$.ajax({
			url: "getUsers",
			success: function (res) {
				console.log(res);
				$("#hyList").empty();
				let users = res.data;
				let userInfo = "";
				for (let i = 0; i < users.length; i++) {
					let name = users[i];
					userInfo = userInfo + '<a style="text-align: center; display: block;" onclick="showChat(\'' + name + '\')">' + name + '</a>';
				}
				$("#hyList").append(userInfo);
			},
			async: false //同步请求，只有上面好了才会接着下面
		});
	}

	function sendMsg(ws) {
		//1.获取输入的内容
		let data = $("#input_text").val();
		//2.清空发送框
		$("#input_text").val("");
		let json = {"toName": toName, "message": data};
		//将数据展示在聊天区
		let str = "<span id='mes_right'>" + data + "</span></br>";
		$("#content").append(str);

		let chatData = sessionStorage.getItem(toName);
		if (chatData != null) {
			str = chatData + str;
		}
		sessionStorage.setItem(toName, str);
		//3.发送数据
		ws.send(JSON.stringify(json));
		//发送消息
	}

	$("#submit").click(function () {
		sendMsg(websocket);
	})
</script>
<script src="https://eqcn.ajz.miesnfu.com/wp-content/plugins/wp-3d-pony/live2dw/lib/L2Dwidget.min.js"></script>
<!--小帅哥： https://unpkg.com/live2d-widget-model-chitose@1.0.5/assets/chitose.model.json-->
<!--萌娘：https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json-->
<!--小可爱（女）：https://unpkg.com/live2d-widget-model-koharu@1.0.5/assets/koharu.model.json-->
<!--小可爱（男）：https://unpkg.com/live2d-widget-model-haruto@1.0.5/assets/haruto.model.json-->
<!--初音：https://unpkg.com/live2d-widget-model-miku@1.0.5/assets/miku.model.json-->
<!-- 上边的不同链接显示的是不同的小人，这个可以根据需要来选择 下边的初始化部分，可以修改宽高来修改小人的大小，或者是鼠标移动到小人上的透明度，也可以修改小人在页面出现的位置。 -->
<script>
	/*https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json*/
	L2Dwidget.init({
		"model": {
			jsonPath:
				"https://unpkg.com/live2d-widget-model-shizuku@1.0.5/assets/shizuku.model.json",
			"scale": 1
		}, "display": {
			"position": "right", "width": 110, "height": 150,
			"hOffset": 0, "vOffset": -20
		}, "mobile": {"show": true, "scale": 0.5},
		"react": {"opacityDefault": 0.8, "opacityOnHover": 0.1}
	});
</script>
</html>